package com.example.app1

import android.animation.ObjectAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import androidx.core.graphics.toColorInt
import kotlin.math.max
import kotlin.random.Random

/**
 * xfermode
 * SRC_IN
 * 只有第二张图盖住第一张图时，被盖住的部分才会按照mode生效
 * 而没盖住的部分就按原样显示
 * 也就是说第二张图是重点，第二张图所在区域才生效？
 * 另外还需要用saveLayer-restoreCount抱起来
 * saveLayer
 * draw 1
 * set xfermode = mode
 * draw 2
 * restoreCount
 * set xfermode = null
 * 如果要画一张圆形头像，那么就截取一个正方形layer
 * 画一个大小刚好合适的圆
 * 按照正方形大小拿到头像并画上去
 * 这时头像是完全盖住圆的，按照src_in就可以取头像和圆重叠的头像了
 */
class HistogramView(context: Context?, attrs: AttributeSet?) : View(context, attrs) {

    private var radius = 0f
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private var itemWidth = 0f
    private var itemNumber = 0
    private var itemInterval = 0f
    private var items = ArrayList<Float>()
    private val xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
    private var heightCoefficient = 0f
    private var animationFraction = 0f
        set(value) {
            field = value
            invalidate()
        }

    private val riseAnimation = ObjectAnimator.ofFloat(this, "animationFraction", 0f, 1f)
    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        val list = List(5) { Random.nextFloat() * 100 }
        loadData(list)
        refreshItemArgs()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        drawItem(canvas)
    }

    private fun drawItem(canvas: Canvas) {
        var startOffset = itemInterval / 2
        items.forEach { value ->
            val layer =
                canvas.saveLayer(startOffset, 0f, startOffset + itemWidth, height.toFloat(), paint)
            paint.color = "#FFEFEDED".toColorInt()
            canvas.drawRoundRect(
                startOffset, 0f, startOffset + itemWidth, height.toFloat(), radius, radius, paint
            )
//            canvas.drawRect(
//                startOffset,
//                0f,
//                startOffset + itemWidth,
//                radius,
//                paint
//            )
//            canvas.drawRect(
//                startOffset + itemWidth - radius,
//                0f,
//                startOffset + itemWidth,
//                radius,
//                paint
//            )
            paint.color = Color.BLUE
            paint.xfermode = xfermode
            val currentTop = height - value * heightCoefficient * animationFraction
            canvas.drawRect(
                startOffset, currentTop, startOffset + itemWidth, height.toFloat(), paint
            )
            paint.xfermode = null
            canvas.restoreToCount(layer)
            startOffset += itemWidth + itemInterval
        }
    }

    private fun loadData(data: List<Float>) {
        items.clear()
        items.addAll(data)
        refreshItemArgs()
        riseAnimation.duration = 2000
        postOnAnimation { riseAnimation.start() }
    }

    private fun refreshItemArgs() {
        if (items.isEmpty()) {
            return
        }
        itemNumber = items.size
        val fl = width.toFloat() / itemNumber / 7
        itemInterval = fl
        itemWidth = fl * 6
        radius = itemWidth / 2
        var maxItem = 0f
        for (item in items) {
            maxItem = max(maxItem, item)
        }
        heightCoefficient = height.toFloat() / maxItem
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        if (event.actionMasked == MotionEvent.ACTION_DOWN) {
            val list = List(5) { Random.nextFloat() * 100 }
            loadData(list)
        }
        return false
    }


}